import { Injectable } from '@nestjs/common';
import { WechatConfig } from '@/config/wechat.config';
import { HttpService } from '@nestjs/axios';
import * as crypto from 'crypto';

@Injectable()
export class WechatService {
  constructor(
    private readonly httpService: HttpService, // 正确注入HttpService
  ) {}

  async create(
    js_code: string,
  ): Promise<{ openid: string; session_key: string }> {
    const { getCodeHttpServer } = WechatConfig.wechat;
    const { appId, appSecret } = WechatConfig.apps;

    const requestUrl = getCodeHttpServer
      .replace('${appid}', appId)
      .replace('${secret}', appSecret)
      .replace('${js_code}', js_code);
    try {
      const response = await this.httpService.get(requestUrl).toPromise();
      return {
        openid: response.data.openid,
        session_key: response.data.session_key,
      };
    } catch (error) {
      console.error('调用微信接口失败:', error);
      throw new Error(`获取微信用户信息失败: ${error.message}`);
    }
  }

  /**
   * 解密微信小程序手机号
   * @param sessionKey 微信会话密钥
   * @param encryptedData 加密数据
   * @param iv 加密算法的初始向量
   */
  getWechatBindPhone({ iv, encryptedData, sessionKey }): { phone: string } {
    try {
      const decipher = crypto.createDecipheriv(
        'aes-128-cbc',
        Buffer.from(sessionKey, 'base64'),
        Buffer.from(iv, 'base64'),
      );
      let decrypted = decipher.update(encryptedData, 'base64', 'utf8');
      decrypted += decipher.final('utf8');
      const data = JSON.parse(decrypted) as any;
      console.log(data, '-data--');
      return {
        phone: data.phoneNumber || data.purePhoneNumber || data.phone,
      };
    } catch (error) {
      throw new Error('解密手机号失败: ' + error.message);
    }
  }

  /**
   * 获取用户昵称
   * @param openid 用户openid
   * @param nickName 用户提供的昵称
   */
  /**
   * 解密微信小程序手机号
   * @param sessionKey 微信会话密钥
   * @param encryptedData 加密数据
   * @param iv 加密算法的初始向量
   */
  getWechatBindNickName({ iv, encryptedData, sessionKey }): {
    nickName: string;
  } {
    const decipher = crypto.createDecipheriv(
      'aes-128-cbc',
      Buffer.from(sessionKey, 'base64'),
      Buffer.from(iv, 'base64'),
    );
    let decrypted = decipher.update(encryptedData, 'base64', 'utf8');
    decrypted += decipher.final('utf8');
    const data = JSON.parse(decrypted) as any;
    return {
      nickName: data.nickName,
    };
  }
}
